/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */ 
package administratorGUI;

import java.util.List;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.WARNING_MESSAGE;
import model.*;
import supermarket.EntityManagerFactory;
import supermarket.JTextFieldLimit;

/**
 * Οθόνη Εισαγωγής / Επεξεργασίας Προϊόντος
 */
public class NewProductDialog extends javax.swing.JDialog {

    private boolean mSave = false;
    private boolean isNewRecord;
    private Product product;

    /**
     *
     * @param parent
     * @param modal
     */
    public NewProductDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        initForm();
    }

    /**
     * Ορίζει το Max Length στα JTextFields
     */
    private void initForm() {
        productCode.setDocument(new JTextFieldLimit(10));
        productName.setDocument(new JTextFieldLimit(30));
        productPoints.setDocument(new JTextFieldLimit(3));
        productPrice.setDocument(new JTextFieldLimit(6));
        this.isNewRecord = true;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        productCodeLabel = new javax.swing.JLabel();
        productCode = new javax.swing.JTextField();
        productName = new javax.swing.JTextField();
        productNameLabel = new javax.swing.JLabel();
        productPointsLabel = new javax.swing.JLabel();
        productPriceLabel = new javax.swing.JLabel();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        productPrice = new javax.swing.JFormattedTextField();
        productPoints = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Προϊόν");

        productCodeLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        productCodeLabel.setText("Κωδικός");

        productCode.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        productName.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        productNameLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        productNameLabel.setText("Όνομα");

        productPointsLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        productPointsLabel.setText("Πόντοι");

        productPriceLabel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        productPriceLabel.setText("Τιμή");

        cancelButton.setText("Ακύρωση");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setText("Εγγραφή");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        productPrice.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        productPrice.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00"))));
        productPrice.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        productPoints.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        productPoints.setColumns(3);
        productPoints.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        productPoints.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(productCodeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 52, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(productCode, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 137, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(26, 26, 26)
                                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                                    .add(productPointsLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .add(productPoints, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(54, 54, 54))
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(saveButton)
                                .add(18, 18, 18)))
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(productPrice, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(productPriceLabel)
                            .add(cancelButton)))
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, productNameLabel)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, productName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 329, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .add(0, 16, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(productNameLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(productName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                    .add(productCodeLabel)
                    .add(productPointsLabel)
                    .add(productPriceLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
                    .add(productCode, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(productPoints, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(productPrice, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(39, 39, 39)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(cancelButton)
                    .add(saveButton))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(new java.awt.Component[] {productCode, productName}, org.jdesktop.layout.GroupLayout.VERTICAL);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Button: Ακύρωση
     *
     * @param evt
     */
     private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
         dispose();
         mSave = false;
     }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * Button: Εγγραφή
     *
     * @param evt
     */
     private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        
        // Έλεγχος για υποχρεωτικά πεδία
         String field = "";

         if (productCode.getText().trim().isEmpty()) {
             field = productCodeLabel.getText();
         } else if (productName.getText().trim().isEmpty()) {
             field = productNameLabel.getText();
         } else if (productPoints.getText().trim().isEmpty()) {
             field = productPointsLabel.getText();
         } else if (productPrice.getText().trim().isEmpty()) {
             field = productPriceLabel.getText();
         }

         if (!field.isEmpty()) {
             JOptionPane.showMessageDialog(this, "Το πεδίο '" + field
                     + "' είναι υποχρεωτικό.", "Καταχώρηση", WARNING_MESSAGE);
         } else {
             // Ελέγχω αν ο 'Κωδικός Προϊόντος' είναι unique
             TypedQuery<Product> query = EntityManagerFactory.getEntityManager()
                     .createNamedQuery("Product.findByCode", Product.class)
                     .setParameter("code", this.getProductCode());
             List<Product> list = query.getResultList();

             // Αν δεν υπάρχει εγγραφή στη βάση  
             if (list.isEmpty()) {
                 this.dispose();
                 this.mSave = true;
             }
             else {
                 // Ειδικά για edit mode, ελέγχω ότι βρέθηκε εγγραφή
                 // με διαφορετικό id
                 if (this.isNewRecord || !this.isNewRecord
                         && list.get(0).getProductId() != this.product.getProductId()) {
                     
                         JOptionPane.showMessageDialog(this, "Έχετε ήδη καταχωρήσει "
                                 + "το προϊόν με κωδικό: '" + this.getProductCode() + "'",
                                 "Προσοχή", WARNING_MESSAGE);
                } else {
                    dispose();
                    mSave = true;
                }
             }
         }
     }//GEN-LAST:event_saveButtonActionPerformed

    /**
     * Επιστρέφει τον Κωδικό Προϊόντος
     *
     * @return
     */
    String getProductCode() {
        return productCode.getText();
    }

    /**
     * Επιστρέφει το Όνομα Προϊόντος
     *
     * @return
     */
    String getProductName() {
        return productName.getText();
    }

    /**
     * Επιστρέφει τους Πόντους του Προϊόντος
     *
     * @return
     */
    int getProductPoints() {
        int iProductPoints = 0;
        try {
            iProductPoints = Integer.parseInt(productPoints.getText());
        } catch (Exception e) {
        }

        return iProductPoints;
    }

    /**
     * Επιστρέφει την Τιμή του Προϊόντος
     *
     * @return
     */
    float getProductPrice() {
        float fProductPrice = 0;

        try {
            String price = productPrice.getText();
            price = price.replace(',', '.');
            fProductPrice = Float.parseFloat(price);
        } catch (Exception e) {
        }
        return fProductPrice;
    }

    boolean isValidForSave() {
        return this.mSave;
    }

    /**
     * Γεμίζει τα πεδία της οθόνης (σε edit mode)
     *
     * @param product
     */
    void setProduct(Product product) {

        this.product = product;
        this.isNewRecord = false;

        productCode.setText(product.getCode().trim());
        productName.setText(product.getName().trim());
        productPoints.setText(product.getPoints().toString());
        productPrice.setValue(product.getPrice());
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField productCode;
    private javax.swing.JLabel productCodeLabel;
    private javax.swing.JTextField productName;
    private javax.swing.JLabel productNameLabel;
    private javax.swing.JFormattedTextField productPoints;
    private javax.swing.JLabel productPointsLabel;
    private javax.swing.JFormattedTextField productPrice;
    private javax.swing.JLabel productPriceLabel;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}
